package com.zky.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.MessageListener;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Slf4j
@Configuration
@ConditionalOnClass({ RabbitTemplate.class, MessageListener.class })
public class RabbitConfig {

    @Bean
    public RabbitTemplate rabbitTemplate(CachingConnectionFactory factory) {
        RabbitTemplate template = new RabbitTemplate(factory);

        // 设置 Confirm 回调（消息是否到达交换机）
        template.setConfirmCallback((correlationData, ack, cause) -> {
            if (ack) {
                log.debug("消息发送到交换机");
            } else {
                log.error("消息发送失败: {}" , cause);
            }
        });

        // 设置 Return 回调（消息是否路由到队列）
        template.setReturnCallback((message, replyCode, replyText, exchange, routingKey) -> {
            log.error("消息未路由到队列:{}"," message: "+message+" exchange: "+exchange+" routingKey: "+routingKey);
        });

        // 开启 Mandatory（Return 回调生效）
        template.setMandatory(true);
        return template;
    }
}
